package com.itxzh.logindemo.controller;

import com.itxzh.logindemo.entities.Users;
import com.itxzh.logindemo.service.UsersService;
import com.itxzh.logindemo.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

/**
 * 登入的Controller
 *
 * @Author ldt
 * @Date 2022/5/20 14:34
 * @Version 1.0.0
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    UsersService usersService;

    @RequestMapping("/login")
    public Map<String, Object> login(Users user) {
        HashMap<String, Object> ret = new HashMap<>();
        try {
            Users user0 = usersService.login(user);

            Map<String, String> payload = new HashMap<>();
            payload.put("id", String.valueOf(user0.getId()));
            payload.put("name", user0.getName());

            String token = JwtUtil.getToken(payload);

            ret.put("status", 1);
            ret.put("msg", "认证成功");
            ret.put("data", token);

        } catch (Exception e) {
            ret.put("status", -1);
            ret.put("msg", e.getMessage());
        }

        return ret;
    }
}
